package dao

import (
	"time"

	"github.com/astaxie/beego/orm"

	"learn-otp/models"
)

type LogDao struct {
}

func (dao *LogDao) GetLogs(accoutName, appName string, pageIndex, pageSize int64) (int64, []models.Log, error) {
	dbOrm := orm.NewOrm()

	params := make([]interface{}, 0)

	where := " "
	if accoutName != "" {
		where += "where account_name=?"
		params = append(params, accoutName)
	}
	if appName != "" {
		if len(where) > 1 {
			where += " and app_name=?"
		} else {
			where += "where app_name=?"
		}
		params = append(params, appName)
	}

	order := " order by id desc"
	limit := " limit ?,?"

	var count int64
	sql := "select count(1) from logs"
	if len(where) > 1 {
		sql += where
	}
	qs := dbOrm.Raw(sql, params...)
	err := qs.QueryRow(&count)
	if err != nil {
		return count, nil, err
	}

	sql = "select id,account_name,app_name,passcode,result,create_time from logs"
	if len(where) > 1 {
		sql += where
	}
	sql += (order + limit)
	params = append(params, pageSize*(pageIndex-1), pageSize)

	qs = dbOrm.Raw(sql, params...)
	var logs []models.Log
	_, err = qs.QueryRows(&logs)
	if err != nil {
		return count, nil, err
	}

	return count, logs, nil
}

func (dao *LogDao) AddLog(log *models.Log) error {
	dbOrm := orm.NewOrm()

	log.CreateTime = time.Now()

	rs := dbOrm.Raw("insert into logs(account_name,app_name,passcode,result,create_time) values(?,?,?,?,?)",
		log.AccountName, log.AppName, log.Passcode, log.Result, log.CreateTime)
	result, err := rs.Exec()
	if err != nil {
		return err
	}

	id, err := result.LastInsertId()
	if err != nil {
		return err
	}
	log.Id = id

	return nil
}
